package me.kafeitu.demo.activiti.task;

import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.JavaDelegate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Component
public class AsyncSendMailTask implements JavaDelegate {
	
	@Autowired
	private JavaMailSender mailSender;
	
	private String from = "370020694@qq.com";
	
    @Async
    public void sendMailAsyncMethod(String to, String subject, String content){
         //执行发邮件操作
		SimpleMailMessage message = new SimpleMailMessage();
		message.setFrom(from);
		message.setTo(to);
		message.setSubject(subject);
		message.setText(content);
		mailSender.send(message);
    }
    
    @Async
    public void sendHtmlMailAsyncMethod(String to, String subject, String content) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();
        //true表示需要创建一个multipart message
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content, true);
        mailSender.send(message);
    }

	@Override
	public void execute(DelegateExecution execution) {
		String subject = (String) execution.getVariable("subject");
		String content = (String) execution.getVariable("content");
		String to = (String) execution.getVariable("to");
		
		sendMailAsyncMethod(to,subject,content);
		
	}

}
